package com.exsun.ex1077.ui.fragment.vehicleinfo

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import androidx.coordinatorlayout.widget.CoordinatorLayout
import com.drake.brv.utils.divider
import com.drake.brv.utils.linear
import com.drake.brv.utils.models
import com.drake.brv.utils.setup
import com.exsun.ex1077.R
import com.exsun.ex1077.databinding.FragmentVehicleInfoBinding
import com.exsun.ex1077.network.entity.MapVehicle
import com.exsun.ex1077.network.entity.Mileage
import com.exsun.ex1077.network.entity.VehicleTrackSocket
import com.github.aachartmodel.aainfographics.aachartcreator.*
import com.github.aachartmodel.aainfographics.aaoptionsmodel.AAScrollablePlotArea
import com.github.aachartmodel.aainfographics.aatools.AARgb
import com.google.android.material.appbar.AppBarLayout
import com.zhangping.fastjetpack.base.BaseFragment
import com.zhangping.fastjetpack.binding.gone
import com.zhangping.fastjetpack.binding.visible
import com.zhangping.fastjetpack.extend.*
import com.zhangping.fastjetpack.extend.base.parseState
import com.zhangping.fastjetpack.network.websocket.WebSocketManager
import kotlinx.android.synthetic.main.fragment_vehicle_info.*
import java.util.*
import kotlin.collections.ArrayList

/**
 * 描述：车辆信息
 * 作者：ZhangPing
 * 创建时间：2022/8/10 10:52
 */
class VehicleInfoFragment: BaseFragment<VehicleInfoViewModel, FragmentVehicleInfoBinding>() {

    override fun layoutId() = R.layout.fragment_vehicle_info

    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.vm = mViewModel
        mViewModel.model.set(requireArguments().getSerializable("model") as MapVehicle?)
        super.initView(savedInstanceState)
        millageListView.linear().divider {
            setDivider(1, true)
            setColor(R.color.divider.toColorRes())
        }.setup {
            addType<Mileage>(R.layout.list_item_milleage)
        }
        appBarLayout.addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { appBarLayout, verticalOffset ->
            backTop.visible(verticalOffset < -dp2px(100))
        })
        backTop.setOnClickListener {
            ((appBarLayout.layoutParams as CoordinatorLayout.LayoutParams).behavior as AppBarLayout.Behavior).topAndBottomOffset = 0
            backTop.gone()
        }
        mViewModel.loadMileageData(getMonthFirstDate().toDateStr(with000000 = true), Date().toDateStr(with235959 = true))
        mViewModel.loadVehicleData()
    }

    @SuppressLint("ClickableViewAccessibility")
    private fun initChart(list: List<Mileage>? = null){
        val newList = ArrayList(list ?: emptyList()).reversed()
        val option = AAChartModel()
            .chartType(AAChartType.Column)
            .legendEnabled(false)
            .xAxisGridLineWidth(0.5F)
            .yAxisLineWidth(0F)
            .yAxisGridLineWidth(0.5F)
            .yAxisTitle("")
            .categories(newList.map { it.date.toDateStr("MM-dd", "yyyy-MM-dd") }.toTypedArray())
            .scrollablePlotArea(AAScrollablePlotArea().apply {
                minWidth = 500
                opacity = 1.0F
                scrollPositionX(0F)
            })
            .series(arrayOf(
                AASeriesElement()
                    .name("KM")
                    .color(AARgb(60, 123, 248, 1F))
                    .data(newList.map { it.value.toDouble() }.toTypedArray()))
            ).aa_toAAOptions()
        option.yAxis?.labels?.format = "{value}KM"
        chartView.aa_drawChartWithChartOptions(option)
        //解决滑动冲突问题
        chartView.setOnTouchListener(View.OnTouchListener { v, event ->
            chartView.requestDisallowInterceptTouchEvent(true)
            return@OnTouchListener false
        })
    }

    fun loadMileageData(startTime: String, endTime: String){
        mViewModel.loadMileageData(startTime, endTime)
    }

    override fun createObserver() {
        super.createObserver()
        mViewModel.apply {
            mileageResult.observe(this@VehicleInfoFragment){
                parseState(it, {
                    val list = it ?: emptyList()
                    progressBar.gone()
                    initChart(list)
                    millageListView.models = list.reversed()
                })
            }
            mapVehicleGpsResult.observe(this@VehicleInfoFragment){
                parseState(it, {
                    it?.let {
                        model.set(model.get()?.apply {
                            spd = it.spd
                            gdt = it.gdt
                            location = it.location
                        })
                        model.notifyChange()
                    }
                })
            }
        }
        WebSocketManager.apply {
            dataLiveData.observeInFragment(this@VehicleInfoFragment){
                if (it.isNullOrEmpty()) return@observeInFragment
                val socketModel = it.toModel<VehicleTrackSocket>() ?: return@observeInFragment
                socketModel.wgs84ToGcj02()
                mViewModel.apply {
                    model.set(model.get()?.apply {
                        spd = socketModel.spd
                        gdt = socketModel.gdt
                        location = socketModel.poi?.ars ?: ""
                    })
                    model.notifyChange()
                }
            }
        }
    }
}